package com.qfedu.openplateform.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qfedu.openplateform.common.constans.ExceptionDict;
import com.qfedu.openplateform.common.entity.ResponseData;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 系统参数过滤器
 *
 * 每个请求 都必须传递的参数
 * 参数实际上要去 后台管理 系统参数表中获取
 * 现在我们直接写死 必须的哪些参数 等微服务时再去获取
 *
 * 目前可以暂时写死必传参数  sign ，time  ,method  app_key 必传参数 没有传递 则拒绝
 *
 * /sztest?time=2021-08-27 10:59:39sign=A23B2AC0D7AA2CF89C825BB596140D9A&token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImlhdCI6MTYzMDAzMjc5MiwiZXhwIjoxNjMwMDM2MzkyLCJ1c2VybmFtZSI6ImFkbWluIn0.8h1OyNVuSNn0MuS0CWpogz17Ttxr8frIIhMr-SOpuOo
 *
 *
 */

public class SystemParamFilter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, String[]> map = request.getParameterMap();
        Set<String> keySet = map.keySet();
        List<String> list = Arrays.asList("sign", "time", "method", "app_key");
        if (keySet.containsAll(list)) {
            return true;
        }
        response.setContentType("application/json;charset=utf-8");
        ResponseData bean = new ResponseData();
        bean.setCode(ExceptionDict.SYSTEMPARAM_IDEMPOTENTS_ERROR);
        bean.setMessage("参数错误");
        try {
            response.getWriter().println(JSON.toJSONString(bean));
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }
        return false;
    }
}
